package feng.demo.controller.cus;

import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import feng.demo.entity.*;
import feng.demo.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/cus/order")
public class CusOrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    OrditemService orditemService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    CommodityService commodityService;
    @Autowired
    UserService userService;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    CartService cartService;
    @PostMapping("/goadd")
    @Transactional(rollbackFor = Exception.class)
//    购物车转订单
    public String goadd(Orders orders) throws Exception{
//        获取购物车转订单用户信息
        Object phone = StpUtil.getLoginId();
        User user = userService.findByPhone(String.valueOf(phone));
        orders.setUser(user);
        Double d=0.00;//定义总金额

        for (Orditem o:orders.getOrditems()) {//遍历上传的订单详情中的商品
            Commodity commodity = commodityService.findById(o.getCommodity().getComid());
            if (commodity.getStock()<o.getNum()){//判断商品库存
                throw new Exception(new XJson(401,"库存不足","").toString());
            }else {
                Orditem orditem = new Orditem();//创建订单详情将信息放进去
                orditem.setCommodity(commodity);
                orditem.setNum(o.getNum());
                orditem.setPrice(o.getPrice());
                orditem.setUser(commodity.getUser());
                o=orditem;//替换订单详情
            }
            d=d+commodity.getPrice();//商品金额相加获取总金额
            commodity.setStock(commodity.getStock()-o.getNum());//商品减库存
            commodity.setSales(commodity.getSales()+o.getNum());//商品加销量
            commodityService.update(commodity);//更改
        }
        orders.setAmount(d);//总金额放进订单头
        Integer adds = orderService.adds(orders);//添加订单头
        for (Orditem o:orders.getOrditems()) {//遍历订单详情
                Order order = new Order();
                order.setOrdid(orders.getOrdid());
                o.setOrder(order);//将订单头id加到订单详情
                orditemService.add(o);//添加订单详情
                o.setItemid(o.getItemid());
                cartService.delUidComid(user.getUid(),o.getCommodity().getComid());
        }
        String id=objectMapper.writeValueAsString(orders.getOrdid());
        String s = objectMapper.writeValueAsString(orders);
        redisTemplate.opsForHash().put("orders",id,s);
        return new XJson(200,"下单成功，订单号"+orders.getOrdid(),orders.getOrdid()).toString();
    }

    @GetMapping("/findByOrdid/{id}")
    public String findByOrdid(@PathVariable("id")Integer ordid){

        Orders orders = orderService.findByIds(ordid);

        return new XJson(200,"",orders).toString();
    }

    @GetMapping("/updatepay/{id}")
    public String updatebay(@PathVariable("id")Integer ordid){
        Order order = new Order();
        order.setOrdid(ordid);
        order.setPayment(1);
        order.setPaydate(new Date());
        orderService.update(order);
        return new XJson(200,"付款成功","").toString();
    }

    @GetMapping("/findAll/{p}/{l}")
    public String findAll(@PathVariable("p")Integer p,@PathVariable("l")Integer l){
        Object phone = StpUtil.getLoginId();
        User user = userService.findByPhone(String.valueOf(phone));
        Map<String,Object> map=new HashMap<>();
        List<Orders> list = orderService.findByCusLimit(user.getUid(), p, l);
        int count = orderService.findCountByUid(user.getUid());
        map.put("orders",list);
        map.put("count",count);
        return new XJson(200,"",map).toString();
    }

    @GetMapping("/updatetign/{id}/{p}/{l}")
    public String updatetign(@PathVariable("id")Integer ordid,@PathVariable("p")Integer p,@PathVariable("l")Integer l){
        Order order = new Order();
        order.setOrdid(ordid);
        order.setTsign(new Date());
        orderService.update(order);
        Object phone = StpUtil.getLoginId();
        User user = userService.findByPhone(String.valueOf(phone));
        Map<String,Object> map=new HashMap<>();
        List<Orders> list = orderService.findByUidLimit(user.getUid(), p, l);
        int count = orderService.findCountByUid(user.getUid());
        map.put("orders",list);
        map.put("count",count);
        return new XJson(200,"成功签收",map).toString();

    }


}
